from fastapi import APIRouter, HTTPException, Query
from typing import Optional, List
from ..services.stock_service import StockService
import plotly.graph_objects as go
import plotly.express as px
import json

router = APIRouter(prefix="/api/stock", tags=["股票数据"])

stock_service = StockService()

@router.get("/financial/{stock_code}")
async def get_stock_financial(stock_code: str):
    """
    获取指定股票的财务数据
    """
    try:
        result = stock_service.get_stock_financial_data(stock_code)
        if "error" in result:
            raise HTTPException(status_code=400, detail=result["error"])
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"服务器错误: {str(e)}")

@router.get("/query")
async def query_financial_data(
    stock_code: Optional[str] = Query(None, description="股票代码"),
    start_year: Optional[int] = Query(None, description="开始年份"),
    end_year: Optional[int] = Query(None, description="结束年份")
):
    """
    动态查询财务数据
    """
    try:
        data = stock_service.query_financial_data_from_db(stock_code, start_year, end_year)
        return {"data": data, "count": len(data)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"查询失败: {str(e)}")

@router.get("/stocks")
async def get_available_stocks():
    """
    获取所有可用的股票列表
    """
    try:
        stocks = stock_service.get_available_stocks()
        return {"stocks": stocks}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取股票列表失败: {str(e)}")

@router.get("/chart/{stock_code}")
async def get_stock_chart(
    stock_code: str,
    start_year: Optional[int] = Query(None, description="开始年份"),
    end_year: Optional[int] = Query(None, description="结束年份")
):
    """
    生成股票财务数据图表
    """
    try:
        # 从数据库获取数据，支持年份范围筛选
        data = stock_service.query_financial_data_from_db(
            stock_code=stock_code,
            start_year=start_year,
            end_year=end_year
        )
        
        if not data:
            raise HTTPException(status_code=404, detail="未找到该股票的数据")
        
        # 准备图表数据
        years = [item['year'] for item in data]
        revenues = [item['revenue'] for item in data]
        net_profits = [item['net_profit'] for item in data]
        stock_name = data[0]['stock_name'] if data else "未知股票"
        
        # 创建双轴图表
        fig = go.Figure()
        
        # 添加营业收入柱状图
        fig.add_trace(go.Bar(
            x=years,
            y=revenues,
            name='营业收入',
            yaxis='y',
            marker_color='lightblue'
        ))
        
        # 添加净利润折线图
        fig.add_trace(go.Scatter(
            x=years,
            y=net_profits,
            mode='lines+markers',
            name='净利润',
            yaxis='y2',
            line=dict(color='red', width=3),
            marker=dict(size=8)
        ))
        
        # 生成标题，包含年份范围信息
        title_parts = [f'{stock_name}({stock_code})']
        if start_year and end_year:
            title_parts.append(f'{start_year}-{end_year}年')
        elif start_year:
            title_parts.append(f'{start_year}年起')
        elif end_year:
            title_parts.append(f'{end_year}年止')
        else:
            title_parts.append('近年')
        title_parts.append('财务数据')

        chart_title = ' '.join(title_parts)

        # 设置布局
        fig.update_layout(
            title=chart_title,
            xaxis=dict(title='年份'),
            yaxis=dict(
                title='营业收入 (元)',
                side='left'
            ),
            yaxis2=dict(
                title='净利润 (元)',
                side='right',
                overlaying='y'
            ),
            legend=dict(x=0.01, y=0.99),
            hovermode='x unified'
        )
        
        # 转换为JSON格式返回
        chart_json = fig.to_json()
        
        return {
            "chart_data": json.loads(chart_json),
            "stock_info": {
                "code": stock_code,
                "name": stock_name,
                "data_points": len(data)
            }
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"生成图表失败: {str(e)}")
